package com.example.mydy;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.mydy.model.Task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder> {
    private List<Task> taskList;
    private OnTaskClickListener listener;

    public interface OnTaskClickListener {
        void onTaskClick(Task task);
    }

    public TaskAdapter(List<Task> taskList, OnTaskClickListener listener) {
        this.taskList = taskList;
        this.listener = listener;
    }

    @NonNull
    @Override
    public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_task, parent, false);
        return new TaskViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
        Task task = taskList.get(position);
        
        if (holder.tvTitle != null) {
            holder.tvTitle.setText(task.getTitle());
        }
        
        // 设置任务状态
        if (holder.tvStatus != null) {
            String status = task.getStatus();
            holder.tvStatus.setText(getStatusText(status));
            
            // 根据状态设置不同背景色
            if (Task.STATUS_PENDING.equals(status)) {
                holder.tvStatus.setBackgroundColor(Color.parseColor("#FFA000")); // 黄色
            } else if (Task.STATUS_APPROVED.equals(status) || Task.STATUS_COMPLETED.equals(status)) {
                holder.tvStatus.setBackgroundColor(Color.parseColor("#4CAF50")); // 绿色
            } else if (Task.STATUS_REJECTED.equals(status)) {
                holder.tvStatus.setBackgroundColor(Color.parseColor("#F44336")); // 红色
            } else if (Task.STATUS_IN_PROGRESS.equals(status)) {
                holder.tvStatus.setBackgroundColor(Color.parseColor("#2196F3")); // 蓝色
            } else {
                holder.tvStatus.setBackgroundColor(Color.parseColor("#757575")); // 灰色
            }
        }
        
        // 显示任务链接（如果有）
        if (holder.layoutTaskLink != null && holder.tvTaskLink != null) {
            String link = task.getLink();
            if (!TextUtils.isEmpty(link)) {
                holder.layoutTaskLink.setVisibility(View.VISIBLE);
                holder.tvTaskLink.setText(link);
            } else {
                holder.layoutTaskLink.setVisibility(View.GONE);
            }
        }
        
        // 显示任务内容
        if (holder.tvContent != null) {
            String content = task.getContent();
            if (!TextUtils.isEmpty(content)) {
                holder.tvContent.setVisibility(View.VISIBLE);
                holder.tvContent.setText(content);
            } else {
                holder.tvContent.setVisibility(View.GONE);
            }
        }
        
        // 显示任务奖励（如果有）
        if (holder.tvReward != null) {
            double reward = task.getReward();
            if (reward > 0) {
                holder.tvReward.setVisibility(View.VISIBLE);
                holder.tvReward.setText(String.format("奖励: ¥%.2f", reward));
            } else {
                holder.tvReward.setVisibility(View.GONE);
            }
        }
        
        // 显示任务图片（如果有）
        if (holder.ivTaskImage != null) {
            String imageUrl = task.getImageUrl();
            if (!TextUtils.isEmpty(imageUrl)) {
                holder.ivTaskImage.setVisibility(View.VISIBLE);
                Glide.with(holder.itemView.getContext())
                        .load(imageUrl)
                        .placeholder(R.drawable.placeholder_image)
                        .error(R.drawable.error_image)
                        .into(holder.ivTaskImage);
            } else {
                holder.ivTaskImage.setVisibility(View.GONE);
            }
        }
        
        // 显示拒绝原因（如果任务被拒绝）
        if (holder.layoutRejectReason != null && holder.tvRejectReason != null) {
            if (Task.STATUS_REJECTED.equals(task.getStatus()) && !TextUtils.isEmpty(task.getRejectReason())) {
                holder.layoutRejectReason.setVisibility(View.VISIBLE);
                holder.tvRejectReason.setText(task.getRejectReason());
            } else {
                holder.layoutRejectReason.setVisibility(View.GONE);
            }
        }
        
        // 显示任务提交时间
        if (holder.tvSubmissionTime != null && task.getCreatedAt() != null) {
            String formattedDate = formatDate(task.getCreatedAt());
            holder.tvSubmissionTime.setText("提交时间: " + formattedDate);
        }
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onTaskClick(task);
            }
        });
    }
    
    private String getStatusText(String status) {
        if (Task.STATUS_PENDING.equals(status)) {
            return "待审核";
        } else if (Task.STATUS_APPROVED.equals(status)) {
            return "已通过";
        } else if (Task.STATUS_REJECTED.equals(status)) {
            return "已拒绝";
        } else if (Task.STATUS_IN_PROGRESS.equals(status)) {
            return "处理中";
        } else if (Task.STATUS_COMPLETED.equals(status)) {
            return "已完成";
        } else {
            return "未知状态";
        }
    }
    
    private String formatDate(String dateString) {
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            Date date = inputFormat.parse(dateString);
            return outputFormat.format(date);
        } catch (Exception e) {
            return dateString;
        }
    }

    @Override
    public int getItemCount() {
        return taskList != null ? taskList.size() : 0;
    }

    static class TaskViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        TextView tvStatus;
        LinearLayout layoutTaskLink;
        TextView tvTaskLink;
        TextView tvContent;
        TextView tvReward;
        ImageView ivTaskImage;
        LinearLayout layoutRejectReason;
        TextView tvRejectReason;
        TextView tvSubmissionTime;

        TaskViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tv_task_title);
            tvStatus = itemView.findViewById(R.id.tv_task_status);
            layoutTaskLink = itemView.findViewById(R.id.layout_task_link);
            tvTaskLink = itemView.findViewById(R.id.tv_task_link);
            tvContent = itemView.findViewById(R.id.tv_task_content);
            tvReward = itemView.findViewById(R.id.tv_task_reward);
            ivTaskImage = itemView.findViewById(R.id.iv_task_image);
            layoutRejectReason = itemView.findViewById(R.id.layout_task_reject_reason);
            tvRejectReason = itemView.findViewById(R.id.tv_task_reject_reason);
            tvSubmissionTime = itemView.findViewById(R.id.tv_task_submission_time);
        }
    }
} 